<?php
	require_once('../includes/config.php');
	require_once('../includes/functions.php');
	
	// Retrieve base HTML
	$pageStr = buildStandardPage('Register', 'Register User');
	
	$content = '';
	
	if(isMobile()){
		$content .= 'Detected Mobile!';
	}
	else{
	
		$userAttributes = getUserAttributes();
			
		  if(false == isset($_POST['submit'])){
		  
			$content = '<form name=addForm method=post action='. $_SERVER['PHP_SELF'] 
					 . ' onSubmit="return validateForm(addForm)" >'
					.'<table border=1 cellpadding=2 width=650>';
			  
			  // These attributes will not be displayed in the HTML form to capture user info
			  unset($userAttributes['roleid']);
			  unset($userAttributes['active']);
			  unset($userAttributes['accountNumber']);
			  
			  // Piece together a table that contains 
			  foreach($userAttributes as $heading => $description){
				  $content .= '<tr><td>';
				  if('passwordhash' == $heading or 'confirmPassword' == $heading){
						$content .= $description 
								. '</td><td><input type=password name=' 
								. $heading . '>';
				  }
				  else if('question' == $heading){
					  $content .= $description 
					  . '</td><td><input type=text name=' . $heading . ' style="width: 350px;" >';					  
				  }
				  else if('state' == $heading){
					  $content .= getStatesAsOptions(true);
				  }
				  else if('dob' == $heading){
					  $content .= $description . ' (yyyy-mm-dd)' 
					  . '</td><td><input type=text name=' . $heading . ' >';					  
				  }
				  else if('ssn' == $heading){
					  $content .= $description . ' (x-xx-xxx)' 
					  . '</td><td><input type=text name=' . $heading . ' >';					  
				  }
				  else{
					  $content .= $description 
						. '</td><td><input type=text name=' . $heading . ' >';
				  }
				  $content .= '</td></tr>';
			  }
			  
			  if(true == isBankManager() || true == isAdmin()){
				  $content .= getUserRolesAsOptions();
				  $content .= getActiveOptions();
			  }
			  else{
				  $content .= '<input type=hidden value=2 name=roleid>'
				  . '<input type=hidden value=0 name=active>';
			  }
			  
			  $content .= '</table><input type=submit name=submit value=Submit>';
			  
			  // If a bank employee cancels creating a user they are redirected to the list of users
			  if(true == isBankManager() || true == isAdmin()){
				  $content .= '<input type=button name=cancel value=Cancel onclick="window.location=\''. $USERS_URL . '\'" >';
			  }
			  // if a public user cancels registering as a new user they are redirected to the homepage.
			  else{
				  $content .= '<input type=button name=cancel value=Cancel onclick="window.location=\''. $SITE_URL . '\'" >';
			  }
			  $content .= '<input type=reset value=Reset></form>';
		  }
		  else{			  
			  $tempArray = cleanPost($_POST);
			  
			  // generate a new salt that will be used for security and hashing
			  $salt = uniqid(mt_rand());	
			  
			  // Let's make sure the user doesn't already exist!
			  $insertUserQuery = buildSelectStatement('user', array('email'=>$tempArray['email']));
			  $result = executeSQL($insertUserQuery, 'Failed to add the new user.');
			  $result = mysql_num_rows($result);
			  
			  // This email address isn't associated with a person, we can create a new user.
			  if($result == 0){
				  // Remove the information that MUST NOT go into the database
				  unset($tempArray['confirmPassword']);
				  unset($tempArray['submit']);
				  
				  if(false == isset($tempArray['roleid'])){
					  $tempArray['roleid'] = 2;

				  }
				  
				  // Since the salt is random for each person, we'll use it as our account random number generator.
				  $tempArray['accountNumber'] = substr($salt, 0,6);			  
				  date_default_timezone_set('America/Chicago'); 
				  $tempArray['dob'] = strftime("%Y-%m-%d", strtotime($_POST['dob']));
				  
				  // Add the information that MUST go into the database
				  $tempArray['passwordhash'] = hash('sha256', $tempArray['passwordhash'] . $salt );
				  $tempArray['answerhash'] = hash('sha256', $tempArray['answerhash'] . $salt );
				  $tempArray['salt'] = $salt;
				  
				  $insertUserQuery = buildInsertStatement('user', $tempArray);
				  $result = executeSQL($insertUserQuery, 'Failed to add the new user.');
				  
				  $maxID = getMaxID('user');
							  
				  // The default account is created to be active if the bank manager adds this user to the system.
				  // Furthermore, we assume that the customer deposited $25 to account for the minimum balance.
				  $defaultAccountActive = false;
				  $defaultAccountBalance = 0;
				  if(true == isBankManager() && $tempArray['active'] == 1){
					  $defaultAccountActive = true;
					  $defaultAccountBalance = 25.00;
				  }
				  
				  $insertAccountQuery = buildInsertStatement('account', array('userid' => $maxID, 
																 'type' => 'Savings',
																 'minimum'=> '25',
																 'balance' =>$defaultAccountBalance,
																 'active' => $defaultAccountActive));

				 $result = executeSQL($insertAccountQuery, 'Failed to insert into the database.');
				  
				  // create the transaction that is associated with the creation of the first account (with a deposit of the required $25 min)
				  if(true == $defaultAccountActive){
					  date_default_timezone_set('America/Chicago');
					  $maxID = getMaxID('account');
				  
					  $insertTransactionQuery = buildInsertStatement('transaction', array('accountid' => $maxID,
																	 'type' => 'Deposit',
																	 'amount'=>'25.00',
																	 'balance'=>'25.00',
																	 'date'=>date("Y-m-d")));
				  
					  $result = executeSQL($insertTransactionQuery, 'Failed to insert into the database.');
				  }
				  
				  if(true == isBankManager() || true == isAdmin()){
					  header('Location: ' . $USERS_URL);
				  }
				  else{
					  $content .= 'Thank you for registering with HolderFinancial. Please go to your nearest physical bank to activate your account.';
				  }
			  }
			  else{ //This email address is already used
				  $content .= 'Sorry, the email you entered is already associated with another person. Please register with a different email address.';
			  }
		  }
	}
	
	$pageStr = str_Replace('<!--content-->', $content, $pageStr);
	echo $pageStr;
?>